package com.axa.mule.transformer;

import java.io.InputStream;

import javax.activation.DataHandler;
import javax.mail.util.ByteArrayDataSource;

import org.mule.api.MuleMessage;
import org.mule.api.transformer.TransformerException;
import org.mule.config.i18n.MessageFactory;
import org.mule.transformer.AbstractMessageTransformer;

public class HSSFAttachmentTransformer extends AbstractMessageTransformer {
	
	public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException {
	
		Object payload = message.getPayload();
		
		try {
			
			String attachmentName = message.getOutboundProperty("originalFilename");
			
			ByteArrayDataSource doc = new ByteArrayDataSource((InputStream) payload, "application/vnd.ms-excel");
			doc.setName(String.format("%s", attachmentName));
			DataHandler attachment = new DataHandler(doc);
		
			message.addOutboundAttachment(outputEncoding, attachment);
			
			/*
			 * sets email body 
			 */
			message.setPayload(message.getInvocationProperty("report"));
			logger.info(message.getInvocationProperty("report"));
			
		} catch (Exception e) {
			logger.error(e.getMessage());
			message.setPayload(e.getMessage());
			throw new TransformerException(MessageFactory.createStaticMessage("error while closing input stream: "+ e.getMessage()), this);
		}
		
		return message;
	}

}
